<template>
  <div class="picture-upload">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :custom-request="handleUpload"
      :before-upload="beforeUpload"
    >
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传</div>
      </div>
    </a-upload>
  </div>

</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import {uploadAvatarPictureUsingPost, uploadPictureUsingPost} from "@/api/pictureController.ts";

interface Props {
  picture?: API.PictureVO;
  onSuccess?: (newPicture: API.PictureVO) => void;
  spaceId?: number;
  uploadAvatar?: boolean;
}

const props = defineProps<Props>();

const handleUpload = async ({file}: any) => {
  loading.value = true;
  try {
    const params: API.PictureUploadRequest = props.picture ? { id: props.picture.id } : {}
    params.spaceId = props.spaceId;
    let res =null;
    if (props.uploadAvatar){
      res = await uploadAvatarPictureUsingPost(params,{}, file);
    }else {
      res = await uploadPictureUsingPost(params,{}, file);
    }
    if (res.data.code === 0 && res.data.data){
      props.onSuccess?.(res.data.data);
      message.success('上传成功!');
    }else {
      message.error('上传失败!' + message.error(res.data.message));
    }
  }catch (error){
    console.error('图片上传失败', error);
    message.error('图片上传失败!' + error.message);
  }
  loading.value = false;
}



const loading = ref<boolean>(false);




const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传JPG或PNG文件!');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('Image must smaller than 10MB!');
  }
  return isJpgOrPng && isLt10M;
};
</script>
<style scoped>
.picture-upload :deep(.ant-upload){
  width: 100% !important;
  height: 100% !important;
  min-height: 152px;
  min-width: 152px;
}
.picture-upload img {
  max-width: 100%;
  max-height: 300px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
